//
//  FlowWriteVC.swift
//  Employee
//
//  Created by swordjoy on 2017/6/26.
//  Copyright © 2017年 remotevillage. All rights reserved.
//

import UIKit
import Moya
import Photos

class FlowWriteVC: BaseVC {

    var flowId: String!
    var flowTitle: String!
    var refreshBefore: VoidClosure?
    
//  fileprivate var images: [UIImage] = []
    fileprivate var assets = [PHAsset]()
  fileprivate var imageDatas: [Data] = []
  
  fileprivate var tableView: UITableView!
  fileprivate var flowDetail: FlowDetail?
  fileprivate var models = [[String: String]]()
  fileprivate var cancle: Cancellable?
  fileprivate var sendModel = FlowSend()
  fileprivate var selectImageV: SelectImagePopV!
    fileprivate var selectedIndex: [Int] = []
    
    // 记录每次照相后的图片的asset
    fileprivate var assetIdentifier = ""
    fileprivate var cachingManager = PHCachingImageManager()
  
  override func viewDidLoad() {
    super.viewDidLoad()
    create()
    pullData()
  }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        GlobalConfig.baiduStatisticsPageViewStart("填写流程表单")
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        GlobalConfig.baiduStatisticsPageViewEnd("填写流程表单")
    }
  
  deinit {
    if let temp = cancle { temp.cancel() }
  }

}

// MARK: - action

extension FlowWriteVC {
  
  fileprivate func takePhoto() {
    if self.assets.count >= 8 {
      SJHint.show("你已经选择了八张啦")
      return
    }
    
    if GlobalConfig.isAuthorizationVideo() {
      let imagePicker = UIImagePickerController()
      imagePicker.delegate = self
      imagePicker.allowsEditing = true
      imagePicker.sourceType = .camera
      self.present(imagePicker, animated: true, completion: nil)
    }
    
  }
  
  @objc fileprivate func submitAction() {
    for dic in models {
      // 必填项
      if "1" == dic["isNeed"] {
        if "DateRange" == dic["style"] {
          guard let startTime = dic["startTime"], let endTime = dic["endTime"] else { return }
          if startTime.isEmpty || endTime.isEmpty {
            SJHint.show("有必填项未填写!")
            let temp = dic["index"]!.sj.intValue
            let indexPath = IndexPath.init(item: temp, section: 1)
            self.tableView.scrollToRow(at: indexPath, at: .middle, animated: true)
          }
        }
        
        if dic["value"]!.isEmpty {
            SJHint.show("有必填项未填写!")
            let temp = dic["index"]!.sj.intValue
            let indexPath = IndexPath.init(item: temp, section: 0)
            self.tableView.scrollToRow(at: indexPath, at: .middle, animated: true)
            return
        }
      }
        
        if "1" == dic["isNumber"] {
            let number = dic["value"]!
            if !number.sj.isNumberAndPoint {
                SJHint.show("只能填写数字!")
                let temp = dic["index"]!.sj.intValue
                let indexPath = IndexPath.init(item: temp, section: 0)
                self.tableView.scrollToRow(at: indexPath, at: .middle, animated: true)
                return
            }
        }
    }
    
      let temps = models.map { (dic) -> [String: String] in
        var temp = dic
        temp["tag"] = nil
        temp["isNeed"] = nil
        temp["index"] = nil
        temp["isNumber"] = nil
        temp["startTime"] = nil
        temp["endTime"] = nil
        return temp
      }
      
      let data = try? JSONSerialization.data(withJSONObject: temps, options: .prettyPrinted)
      let jsonString = String.init(data: data!, encoding: .utf8)
      
      sendModel.result = jsonString ?? ""
      sendModel.flowId = flowId
      
      SJApp.showHUD()
      // 没有图片
      if assets.isEmpty {
        let _ = FlowRequest.shared.addFlow(model: sendModel, success: { 
            SJHint.show("操作成功")
          self.navigationController?.popViewController(animated: true)
            self.refreshBefore?()
        }, failure: { 

        })
        return
      }
    
    self.imageDatas.removeAll()
    let uploadImages = PhotoHelper.fetchOriginalPhotos(with: assets)
    for image in uploadImages {
        imageDatas.append(image.uploadData)
    }
    
    
      let _ = FileRequest.shared.uploadImages(datas: imageDatas, progressClosure: { (progress) in
      }) { (ids) in
        self.sendModel.imageIds = ids
        let _ = FlowRequest.shared.addFlow(model: self.sendModel, success: {
          SJHint.show("操作成功!")
            self.refreshBefore?()
          self.navigationController?.popViewController(animated: true)
        }, failure: {
          
        })
      }
    
    }
}

extension FlowWriteVC: PhotoPickerDelegate {
    func photoPickerDidFinishSelected(_ assets: [PHAsset]) {
        self.assets += assets
        let indexPath = IndexPath(row: 0, section: 2)
        self.tableView.reloadRows(at: [indexPath], with: .automatic)
    }
}

// MARK: - CheckPeopleCellDelegate

extension FlowWriteVC: CheckPeopleCellDelegate {
    func getApprovalStaffId(ids: String, selectedIndex: [Int]) {
        guard let temp = flowDetail?.flowType else { return }
        if "STAFF" == temp { sendModel.approvalIds = "" }
        else {
            sendModel.approvalIds = ids
            if !selectedIndex.isEmpty {
                self.selectedIndex = selectedIndex
            }
        }
    }
}

// MARK: - UIImagePickerControllerDelegate, UINavigationControllerDelegate

extension FlowWriteVC: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
  
  func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    guard let image = info[UIImagePickerControllerOriginalImage] as? UIImage else {
        return
    }
    
    PHPhotoLibrary.shared().performChanges({ 
        let request = PHAssetChangeRequest.creationRequestForAsset(from: image)
        self.assetIdentifier = request.placeholderForCreatedAsset?.localIdentifier ?? ""
    }) { (finish, error) in
        if nil != error {
            runOnMainThread {
                SJHint.show("获取照片失败, 请重新拍摄")
                picker.dismiss(animated: true) { }
            }
            return
        }
        else {
            let tempAssets = PHAsset.fetchAssets(withLocalIdentifiers: [self.assetIdentifier], options: nil)
            guard let asset = tempAssets.firstObject else {
                runOnMainThread {
                    SJHint.show("获取照片失败, 请重新拍摄")
                    picker.dismiss(animated: true) { }
                }
                return
            }
            self.assets.append(asset)
            let indexPath = IndexPath(row: 0, section: 2)
            self.tableView.reloadRows(at: [indexPath], with: .automatic)
            
            picker.dismiss(animated: true) {
            }
        }
    }
    
   
  }
  
  func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
    picker.dismiss(animated: true) {
    }
  }
  
}

// MARK: - UITableViewDataSource

extension FlowWriteVC: UITableViewDataSource {
  func numberOfSections(in tableView: UITableView) -> Int {
    guard let temp = flowDetail else {
        return 0
    }
    // 如果没有审批人,直接可以提交
    if temp.checkPeoples.isEmpty {
        return 4
    }
    return 5
  }
  
  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if 0 == section { return flowDetail?.formItems.count ?? 0 }
    return 1
  }
  
  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if 0 == indexPath.section {
      let cellType = flowDetail?.formItems[indexPath.row].type ?? ""
      // 单选框
      if "Radio" == cellType {
        let cell = tableView.dequeueReusableCell(withIdentifier: InspectionRadioCell.identifier) as! InspectionRadioCell
        cell.isFlow = true
        if flowDetail?.formItems[indexPath.row].required ?? true {
          cell.name = (flowDetail?.formItems[indexPath.row].name ?? "")
        }
        else {
          cell.name = (flowDetail?.formItems[indexPath.row].name ?? "") + "(选填)"
        }
        cell.titles = flowDetail?.formItems[indexPath.row].options ?? []

        if let tag = self.models[indexPath.row].safeObject(forKey: "tag") {
          if (tag as! String).isEmpty { cell.selectIndex = -1 }
          else { cell.selectIndex = (tag as! String).sj.intValue }
        }
        else { cell.selectIndex = -1 }
        
        cell.getSelect = { (tag, name, title) in
          self.models[indexPath.row]["name"] = name
          self.models[indexPath.row]["value"] = title
          self.models[indexPath.row]["tag"] = tag
        }
        
        self.models[indexPath.row]["style"] = "Radio"
        
        return cell
      }
        // 复选框
      else if "Checkbox" == cellType {
        let cell = tableView.dequeueReusableCell(withIdentifier: InspectionMultiSelectCell.identifier) as! InspectionMultiSelectCell
        cell.isFlow = true
        if flowDetail?.formItems[indexPath.row].required ?? true { cell.name = flowDetail?.formItems[indexPath.row].name ?? ""}
        else { cell.name = (flowDetail?.formItems[indexPath.row].name ?? "") + "(选填)" }
        
        cell.titles = flowDetail?.formItems[indexPath.row].options ?? []
        
        if let tags = self.models[indexPath.row].safeObject(forKey: "tag") {
          // MARK: - 这里不知道为啥会为空字符串
          if !(tags as! String).isEmpty {
            let temps = (tags as! String).components(separatedBy: ",")
            let stringTags = temps.map({
              return $0.sj.intValue
            })
            
            cell.selectIndexs = stringTags
          }
          else { cell.selectIndexs = [] }
        }
        else { cell.selectIndexs = [] }
        
        cell.getSelect = { (tags, name, titles) in
          self.models[indexPath.row]["name"] = name
          self.models[indexPath.row]["value"] = titles
          self.models[indexPath.row]["tag"] = tags
        }
        
        self.models[indexPath.row]["style"] = "Checkbox"
        return cell
      }
        // 其他
      else {
        if "Select" == cellType {
          let cell = tableView.dequeueReusableCell(withIdentifier: InspectionInputCustomCell.identifier) as! InspectionInputCustomCell
          cell.isFlow = true
          cell.options = flowDetail?.formItems[indexPath.row].options ?? []
          cell.type = .pullMenu
          
          if flowDetail?.formItems[indexPath.row].required ?? true { cell.name = flowDetail?.formItems[indexPath.row].name ?? "" }
          else { cell.name = (flowDetail?.formItems[indexPath.row].name ?? "") + "(选填)" }
          
          cell.options = flowDetail?.formItems[indexPath.row].options ?? []
          
          cell.getSelect = { (name, text) in
            self.models[indexPath.row]["name"] = name
            self.models[indexPath.row]["value"] = text
          }
          
          if let text = self.models[indexPath.row].safeObject(forKey: "value") {
            if (text as! String).isEmpty { cell.content = ""}
            else { cell.content = (text as! String)}
          }
          else { cell.content = "" }
          
          self.models[indexPath.row]["style"] = "Select"
          return cell
        }
        else if "Textarea" == cellType || "Input" == cellType {
          let cell = tableView.dequeueReusableCell(withIdentifier: InspectionInputCell.identifier) as! InspectionInputCell
          cell.type = .text
          cell.isFlow = true
          if flowDetail?.formItems[indexPath.row].required ?? true { cell.name = flowDetail?.formItems[indexPath.row].name ?? ""}
          else { cell.name = (flowDetail?.formItems[indexPath.row].name ?? "") + "(选填)" }
          
          cell.getSelect = { (name, text) in
            self.models[indexPath.row]["name"] = name
            self.models[indexPath.row]["value"] = text
          }
          
          if let text = self.models[indexPath.row].safeObject(forKey: "value") {
            if (text as! String).isEmpty { cell.content = ""}
            else { cell.content = (text as! String) }
          }
          else { cell.content = "" }
          
          self.models[indexPath.row]["style"] = "Textarea"
          return cell
        }
        else if "Figure" == cellType {
          let cell = tableView.dequeueReusableCell(withIdentifier: InspectionInputCell.identifier) as! InspectionInputCell
          cell.type = .number
          cell.isFlow = true
          if flowDetail?.formItems[indexPath.row].required ?? true { cell.name = flowDetail?.formItems[indexPath.row].name ?? ""}
          else { cell.name = (flowDetail?.formItems[indexPath.row].name ?? "") + "(选填)" }
          
          cell.getSelect = { (name, text) in
            self.models[indexPath.row]["name"] = name
            self.models[indexPath.row]["value"] = text
          }
          
          if let text = self.models[indexPath.row].safeObject(forKey: "value") {
            if (text as! String).isEmpty { cell.content = "" }
            else { cell.content = (text as! String) }
          }
          else { cell.content = "" }
          
          self.models[indexPath.row]["style"] = "Figure"
          return cell
        }
        else if "Date" == cellType {
          let cell = tableView.dequeueReusableCell(withIdentifier: InspectionInputCustomCell.identifier) as! InspectionInputCustomCell
          cell.type = .date
          cell.options = []
          cell.isFlow = true
          if flowDetail?.formItems[indexPath.row].required ?? true { cell.name = flowDetail?.formItems[indexPath.row].name ?? "" }
          else { cell.name = (flowDetail?.formItems[indexPath.row].name ?? "") + "(选填)" }
          
          cell.getSelect = { (name, text) in
            self.models[indexPath.row]["name"] = name
            self.models[indexPath.row]["value"] = text
          }
          
          if let text = self.models[indexPath.row].safeObject(forKey: "value") {
            if (text as! String).isEmpty { cell.content = "" }
            else { cell.content = (text as! String) }
          }
          else { cell.content = "" }
          
          self.models[indexPath.row]["style"] = "Date"
          return cell
        }
        else if "DateRange" == cellType {
          let cell = tableView.dequeueReusableCell(withIdentifier: DateRangeFormCell.identifier) as! DateRangeFormCell
          cell.model = flowDetail?.formItems[indexPath.row]
          
          if let text = self.models[indexPath.row].safeObject(forKey: "startTime") {
            cell.start = text as! String
          }
          
          if let text = self.models[indexPath.row].safeObject(forKey: "endTime") {
            cell.end = text as! String
          }
          
          cell.getTime = { (start, end , name) in
            self.models[indexPath.row]["name"] = name
            self.models[indexPath.row]["value"] = start + "," + end
            self.models[indexPath.row]["startTime"] = start
            self.models[indexPath.row]["endTime"] = end
          }
          
          self.models[indexPath.row]["style"] = "DateRange"
          return cell
        }
        
        return UITableViewCell()
      }
    }
      // 附件
    else if 1 == indexPath.section {
      let cell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell.swordjoy")!
      cell.backgroundColor = GlobalConfig.BGWhiteColor
      return cell
    }
    else if 2 == indexPath.section {
      let cell = tableView.dequeueReusableCell(withIdentifier: FlowAddCell.identifier) as! FlowAddCell
      cell.delegate = self
      cell.assets = assets
      return cell
    }
    else if 3 == indexPath.section {
      let cell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell.swordjoy")!
      cell.backgroundColor = GlobalConfig.BGWhiteColor
      return cell
    }
    else {
      let cell = tableView.dequeueReusableCell(withIdentifier: CheckPeopleCell.identifier) as! CheckPeopleCell
        let type = flowDetail?.flowType ?? ""
        if !("STAFF" == type) {
            if !sendModel.approvalIds.isEmpty {
                cell.selectedIndex = selectedIndex
            }
        }
        cell.model = flowDetail
      cell.delegate = self
      return cell
    }
  }
}

// MARK: - UITableViewDelegate

extension FlowWriteVC: UITableViewDelegate {
  func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    if 0 == indexPath.section {
      let cellType = flowDetail?.formItems[indexPath.row].type ?? ""
      
      if "Radio" == cellType { return InspectionRadioCell.height(with: flowDetail?.formItems[indexPath.row].options ?? []) }
      else if "Checkbox" == cellType { return InspectionMultiSelectCell.height(with: flowDetail?.formItems[indexPath.row].options ?? []) }
      else if "Textarea" == cellType { return 200 }
      else if "DateRange" == cellType { return 180 }
      else { return 150 }
    }
    else if 1 == indexPath.section {
      return 10
    }
    else if 2 == indexPath.section {
      if assets.count < 4 { return (UIScreen.width - 80) / 4 + 117 }
      else { return (UIScreen.width - 80) / 2 + 117 }
    }
    else if 3 == indexPath.section {
      return 10
    }
    else if 4 == indexPath.section {
      return CheckPeopleCell.height(with: flowDetail?.checkPeoples ?? [])
    }
    return 0
  }
  
  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    
  }
}

extension FlowWriteVC: FlowAddCellDelegate {
  func addPicture() {
    selectImageV.show(in: self.navigationController!.view)
  }
  
  func deletePicture(index: Int) {
    assets.remove(at: index)
    if assets.count < 4 {
      let indexPath = IndexPath(row: 0, section: 2)
      self.tableView.reloadRows(at: [indexPath], with: .none)
    }
  }
  
  func clickPicture(index: Int) {
    
  }
}

// MARK: - fileprivate

extension FlowWriteVC {
  
  fileprivate func pullData() {
    SJApp.showHUD()
    cancle = FlowRequest.shared.getFlowTypeDetail(id: flowId, success: { (data) in
      self.view.addSubview(self.tableView)
      
      self.flowDetail = data
      self.sendModel.flowType = data.flowType
      
      var temps: [String] = []
      for item in data.checkPeoples {
        guard let temp = item.roles.first?.roleStaffId else { continue }
        temps.append(temp)
        self.selectedIndex.append(0)
      }
      self.sendModel.approvalIds = temps.joined(separator: ",")
      
      for (index, item) in data.formItems.enumerated() {
        var dic = Dictionary<String, String>()
        dic["value"] = ""
        
        if item.required {
          dic["name"] = item.name
          dic["isNeed"] = "1"
        } else {
          dic["name"] = item.name + "(选填)"
          dic["isNeed"] = "0"
        }
        
        dic["tag"] = ""
        dic["index"] = "\(index)"
        
        dic["isNumber"] = ""
        if "Figure" == item.type {
          dic["isNumber"] = "1"
        }
        
        dic["startTime"] = ""
        dic["endTime"] = ""
        dic["style"] = ""
        
        self.models.append(dic)
      }
      
      self.tableView.reloadData()
    }, failure: { 
      SJHint.show("获取流程表单失败")
    })
  }
  
  fileprivate func create() {
    view.backgroundColor = GlobalConfig.BGWhiteColor
    title = flowTitle
    addBackItem()
    
    navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "提交", style: .plain, target: self, action: #selector(submitAction))
    
    tableView = UITableView()
    tableView.backgroundColor = UIColor.clear
    tableView.frame = CGRect(x: 10, y: 0, width: UIScreen.width - 20 , height: UIScreen.noNavBarHeight)
    tableView.delegate = self
    tableView.showsVerticalScrollIndicator = false
    tableView.dataSource = self
    tableView.separatorStyle = .none
    
    let headerView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.width, height: 10))
    headerView.backgroundColor = GlobalConfig.BGWhiteColor
    tableView.tableHeaderView = headerView
    
    let footerView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.width, height: 10))
    footerView.backgroundColor = GlobalConfig.BGWhiteColor
    tableView.tableFooterView = footerView
    
    tableView.register(OrderTitleCell.self, forCellReuseIdentifier: OrderTitleCell.identifier)
    tableView.register(InspectionRadioCell.self, forCellReuseIdentifier: InspectionRadioCell.identifier)
    tableView.register(InspectionMultiSelectCell.self, forCellReuseIdentifier: InspectionMultiSelectCell.identifier)
    tableView.register(InspectionInputCell.self, forCellReuseIdentifier: InspectionInputCell.identifier)
    tableView.register(ButtonCell.self, forCellReuseIdentifier: ButtonCell.identifier)
    tableView.register(InspectionInputCustomCell.self, forCellReuseIdentifier: InspectionInputCustomCell.identifier)
    tableView.register(DateRangeFormCell.self, forCellReuseIdentifier: DateRangeFormCell.identifier)
    tableView.register(FlowAddCell.self, forCellReuseIdentifier: FlowAddCell.identifier)
    tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell.swordjoy")
    tableView.register(CheckPeopleCell.self, forCellReuseIdentifier: CheckPeopleCell.identifier)
    
    selectImageV = SelectImagePopV(frame: UIScreen.main.bounds)
    selectImageV.takePhotoClosure = {
      self.takePhoto()
    }
    
    selectImageV.selectClosure = { [unowned self] in
        let vc = PhotoPicker(selectedCount: self.assets.count, maxCount: 8, delegate: self)
        self.navigationController?.pushViewController(vc, animated: true)
    }
  }
  
}
